﻿using Framework.EncryptionService.Abstract;
using System.Security.Cryptography;
using Framework.EncryptionService;

namespace Framework.EncryptionService.Services
{
    /// <summary>
    /// AES加密服务
    /// </summary>
    public class EncryptionAESServiceHelps : AbstractEncryptionServiceHelps<EncryptionAESServiceHelps>
    {
        /// <summary>
        /// AES加密服务
        /// </summary>
        public EncryptionAESServiceHelps() { }
        /// <summary>
        /// AES加密服务
        /// </summary>
        /// <param name="encryption"></param>
        public EncryptionAESServiceHelps(EncryptionServiceHelpsEntity encryption = null) : base(encryption) { }

        public override byte[] Decrypt(byte[] encryptedBytes)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = PrivateSecretKey.FromBase64String();
                aes.IV = PublicSecretKey.FromBase64String();
                ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
                using (MemoryStream ms = new MemoryStream(encryptedBytes))
                {
                    using (CryptoStream cs = new CryptoStream(ms,transform, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            return sr.ReadToEnd().ConvertToBytes();
                        }
                    }
                }
            }
        }

        public override byte[] Encrypt(string data)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = PrivateSecretKey.FromBase64String();
                aes.IV = PublicSecretKey.FromBase64String();
                ICryptoTransform cryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(data);
                        }
                        return ms.ToArray();
                    }
                }
            }
        }

        public override EncryptionServiceHelpsEntity InitEncryption()
        {
            using Aes aes = Aes.Create();
            aes.GenerateKey();
            aes.GenerateIV();
            return new EncryptionServiceHelpsEntity() { PrivateSecretKey = aes.Key.ToBase64String(), PublicSecretKey = aes.IV.ToBase64String() };
        }
    }
}
